<?php
/*
 *   This file is part of Verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 *   Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */ 

if ($op=="rp") {
	$us = new user();
	$us->userid=$param['userid'];
	$ret = $loader->get($us);
	if ($ret) {
		$us->passcode = util::createPassword(MIN_PASSWORD_LEN);
		$us->passexpire = util::now();
		$loader->update($us);
		mailNewPassword($us);
	}
	success(s("Please check your mailbox for your new password")); 
} else {
	$us = new user();
	$us->userid=$param['userid'];
	$ret = $loader->getBy($us,$us->get(true));

	if ($ret) {
		$ret = $us->validate($param['password']);
		//$ret = $us->currentpwd==$param['password'];
		if (!$ret) {
			if ($us->currentpasscode!="" and !util::isExpire($us->passexpire,RECOVERY_EXPIRE)) {
				$_log->debug("Passcode found");
				$ret = $us->validate($param['password'],$us->currentpasscode);
				//$ret = $us->currentpasscode==$param['password'];
			}
			if (!$ret) {
				$_log->debug("Password is invalid");
				$error = s("Invalid Username or password.");	
			}
		}
		if ($ret) {
			$_log->debug("Password valid");
			if ($us->status==STATUS_INACTIVE) {
				$error= s("Your account is disabled.");	
			} else {
				//$_SESSION["s_user"] = $us->userid;
				$loader->execute($us->updateLogin());
				cache('s_user',$us);
				if (isset($param['rememberme']) and $param['rememberme']=="on") {
					setLoginCredentials($us);
				}
			}
		} 
	} else {
		$error = s("Invalid Username or password.");
	}
			
	if (!isset($error)) {
		out("{success: true, target: 'index.php?tx=".rand(1000000000,9999999999)."'}");
	} else {
		out("{success: false, errors: { reason: '$error' }}");
	}	
}

?>

 